/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.cheetah.youbet.gui;

import java.awt.Component;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFormattedTextField;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumnModel;
import org.cheetah.youbet.ContextSpringFactory;
import org.cheetah.youbet.gui.model.PalinsestoTableModel;
import org.cheetah.youbet.gui.popupmenu.PalinsestoPopupMenu;
import org.cheetah.youbet.service.PalinsestoService;
import org.cheetah.youbet.util.comparators.PalinsestoComparator;

/**
 *
 * @author edoardo
 */
public class MainFrame extends javax.swing.JFrame {

    PalinsestoService palinsestoService = ContextSpringFactory.getInstance().getContext().getBean(PalinsestoService.class);

    /**
     * Creates new form MainFrame
     */
    public MainFrame() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        mainPanel = new javax.swing.JPanel();
        showDataSelectorPanel = new javax.swing.JPanel();
        labelDataEvento = new javax.swing.JLabel();
        txtDataEvento = new javax.swing.JFormattedTextField();
        jLabel1 = new javax.swing.JLabel();
        txtOraEvento = new javax.swing.JFormattedTextField();
        bCaricaDatiPalinsesto = new javax.swing.JButton();
        mainScrollPane = new javax.swing.JScrollPane();
        mainTable = new javax.swing.JTable();
        mainBottomButtonBar = new javax.swing.JPanel();
        buttonFirstPage = new javax.swing.JButton();
        buttonPrevPage = new javax.swing.JButton();
        labelPagina = new javax.swing.JLabel();
        labelNumPagina = new javax.swing.JLabel();
        labelPaginaDi = new javax.swing.JLabel();
        labelTotPagine = new javax.swing.JLabel();
        buttonNextPage = new javax.swing.JButton();
        buttonLastPage = new javax.swing.JButton();
        mainMenuBar = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenu2 = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setBounds(new java.awt.Rectangle(0, 22, 1024, 800));
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setPreferredSize(new java.awt.Dimension(1024, 800));

        mainPanel.setLayout(new java.awt.BorderLayout());

        showDataSelectorPanel.setLayout(new java.awt.GridBagLayout());

        labelDataEvento.setText("Data Evento");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.weightx = 0.2;
        gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10);
        showDataSelectorPanel.add(labelDataEvento, gridBagConstraints);

        txtDataEvento.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter(new java.text.SimpleDateFormat("dd/MM/yyyy"))));
        txtDataEvento.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtDataEventoFocusLost(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 0.2;
        gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10);
        showDataSelectorPanel.add(txtDataEvento, gridBagConstraints);
        SimpleDateFormat df =(SimpleDateFormat)SimpleDateFormat.getDateInstance();
        df.applyPattern("dd/MM/yyyy");
        txtDataEvento.setText(df.format(new Date()));

        jLabel1.setText("Ora Evento");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.weightx = 0.2;
        gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10);
        showDataSelectorPanel.add(jLabel1, gridBagConstraints);

        txtOraEvento.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter(new java.text.SimpleDateFormat("HH:mm"))));
        txtOraEvento.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtOraEventoFocusLost(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 0.2;
        gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10);
        showDataSelectorPanel.add(txtOraEvento, gridBagConstraints);
        SimpleDateFormat tf =(SimpleDateFormat)SimpleDateFormat.getTimeInstance();
        tf.applyPattern("HH:mm");
        txtOraEvento.setText(tf.format(new Date()));

        bCaricaDatiPalinsesto.setText("Carica dati");
        bCaricaDatiPalinsesto.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                bCaricaDatiPalinsestoMouseClicked(evt);
            }
        });
        showDataSelectorPanel.add(bCaricaDatiPalinsesto, new java.awt.GridBagConstraints());

        mainPanel.add(showDataSelectorPanel, java.awt.BorderLayout.NORTH);

        mainTable.setModel(new PalinsestoTableModel(        palinsestoService.findPartiteDaGiocare(new Date(),new PalinsestoComparator())) );
        mainTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_ALL_COLUMNS);
        mainTable.setColumnSelectionAllowed(true);
        mainTable.setSelectionMode(javax.swing.ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        mainTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                mainTableMouseReleased(evt);
            }
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                mainTableMouseClicked(evt);
            }
        });
        mainScrollPane.setViewportView(mainTable);
        mainTable.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        //mainTable.setComponentPopupMenu(new PalinsestoPopupMenu());

        mainPanel.add(mainScrollPane, java.awt.BorderLayout.CENTER);

        buttonFirstPage.setText("<<");
        mainBottomButtonBar.add(buttonFirstPage);

        buttonPrevPage.setText("<");
        mainBottomButtonBar.add(buttonPrevPage);

        labelPagina.setText("Pagina");
        mainBottomButtonBar.add(labelPagina);

        labelNumPagina.setText("n");
        mainBottomButtonBar.add(labelNumPagina);

        labelPaginaDi.setText("di");
        mainBottomButtonBar.add(labelPaginaDi);

        labelTotPagine.setText("TOT");
        mainBottomButtonBar.add(labelTotPagine);

        buttonNextPage.setText(">");
        mainBottomButtonBar.add(buttonNextPage);

        buttonLastPage.setText(">>");
        mainBottomButtonBar.add(buttonLastPage);

        mainPanel.add(mainBottomButtonBar, java.awt.BorderLayout.PAGE_END);

        getContentPane().add(mainPanel, java.awt.BorderLayout.CENTER);

        jMenu1.setText("File");
        mainMenuBar.add(jMenu1);

        jMenu2.setText("Edit");
        mainMenuBar.add(jMenu2);

        setJMenuBar(mainMenuBar);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void mainTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_mainTableMouseClicked
        JTable target = (JTable) evt.getSource();
        int row = target.getSelectedRow();
        if (evt.getClickCount() == 2 && SwingUtilities.isLeftMouseButton(evt)) {

            int colCount = target.getColumnCount();
            for (int i = 0; i < colCount; i++) {
//                System.out.print(target.getModel().getValueAt(row, i) + " | ");
            }
        }
//         if(SwingUtilities.isRightMouseButton(evt) && evt.isPopupTrigger()){
//            new PalinsestoPopupMenu().show(evt.getComponent(), evt.getX(), evt.getY());
//        }
//       
    }//GEN-LAST:event_mainTableMouseClicked

    private void mainTableMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_mainTableMouseReleased
        if (SwingUtilities.isRightMouseButton(evt) && !evt.isPopupTrigger()) {
            JTable source = (JTable) evt.getSource();

            int row = source.rowAtPoint(evt.getPoint());
//            int column = source.columnAtPoint(evt.getPoint());

            source.getSelectionModel().addSelectionInterval(row, row);
//                source.changeSelection(row, column, false, false);
            new PalinsestoPopupMenu(source).show(evt.getComponent(), evt.getX(), evt.getY());
        }
    }//GEN-LAST:event_mainTableMouseReleased

    private void txtDataEventoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtDataEventoFocusLost
        JFormattedTextField source = (JFormattedTextField) evt.getSource();
        SimpleDateFormat sdf = (SimpleDateFormat) SimpleDateFormat.getDateInstance();
        sdf.applyPattern("dd/MM/yyyy");
        try {
            Date d = sdf.parse(source.getText());
            Date today = sdf.parse(sdf.format(new Date()));
            if (d.compareTo(today) < 0) {
                JOptionPane.showMessageDialog(this, "La data non puo' essere inferiore alla data odierna.", "Data errata", JOptionPane.ERROR_MESSAGE);
                source.setText(sdf.format(today));
            } 
        } catch (ParseException ex) {
            JOptionPane.showMessageDialog(this, "La data dev'essere nel formato gg/mm/aaaa.", "Errore formato data", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_txtDataEventoFocusLost

    private void loadPalinsesto(Date d) {
        mainTable.setModel(new PalinsestoTableModel(palinsestoService.findPartiteDaGiocare(d,new PalinsestoComparator())));
    }

    private void txtOraEventoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtOraEventoFocusLost
        JFormattedTextField source = (JFormattedTextField) evt.getSource();
        SimpleDateFormat sdf = (SimpleDateFormat) SimpleDateFormat.getTimeInstance();
        sdf.applyPattern("HH:mm");
        try {
            Date d = sdf.parse(source.getText());
        } catch (ParseException ex) {
            JOptionPane.showMessageDialog(this, "L'ora dev'essere nel formato HH:mm.", "Errore formato ora", JOptionPane.ERROR_MESSAGE);
        }
        // TODO add your handling code here:
    }//GEN-LAST:event_txtOraEventoFocusLost

    private void bCaricaDatiPalinsestoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bCaricaDatiPalinsestoMouseClicked
            SimpleDateFormat sdf = (SimpleDateFormat) SimpleDateFormat.getDateInstance();
            SimpleDateFormat stf = (SimpleDateFormat) SimpleDateFormat.getTimeInstance();
            sdf.applyPattern("dd/MM/yyyy");
            stf.applyPattern("HH:mm");
            GregorianCalendar dCalendar = (GregorianCalendar) GregorianCalendar.getInstance();
        try {
            dCalendar.setTime(sdf.parse(txtDataEvento.getText()));
            String ora = txtOraEvento.getText().substring(0,txtOraEvento.getText().indexOf(":"));
            String minuti = txtOraEvento.getText().substring(txtOraEvento.getText().indexOf(":")+1);
            dCalendar.set(Calendar.HOUR, Integer.parseInt(ora));
            dCalendar.set(Calendar.MINUTE, Integer.parseInt(minuti));
            loadPalinsesto(dCalendar.getTime());
        } catch (ParseException ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
            
    }//GEN-LAST:event_bCaricaDatiPalinsestoMouseClicked

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainFrame().setVisible(true);
            }
        });
    }

    public void resizeColumnWidth(JTable table) {
        final TableColumnModel columnModel = table.getColumnModel();
        for (int column = 0; column < table.getColumnCount(); column++) {
            int width = 50; // Min width
            for (int row = 0; row < table.getRowCount(); row++) {
                TableCellRenderer renderer = table.getCellRenderer(row, column);
                Component comp = table.prepareRenderer(renderer, row, column);
                width = Math.max(comp.getPreferredSize().width, width);
            }
            columnModel.getColumn(column).setPreferredWidth(width);
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bCaricaDatiPalinsesto;
    private javax.swing.JButton buttonFirstPage;
    private javax.swing.JButton buttonLastPage;
    private javax.swing.JButton buttonNextPage;
    private javax.swing.JButton buttonPrevPage;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JLabel labelDataEvento;
    private javax.swing.JLabel labelNumPagina;
    private javax.swing.JLabel labelPagina;
    private javax.swing.JLabel labelPaginaDi;
    private javax.swing.JLabel labelTotPagine;
    private javax.swing.JPanel mainBottomButtonBar;
    private javax.swing.JMenuBar mainMenuBar;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JScrollPane mainScrollPane;
    private javax.swing.JTable mainTable;
    private javax.swing.JPanel showDataSelectorPanel;
    private javax.swing.JFormattedTextField txtDataEvento;
    private javax.swing.JFormattedTextField txtOraEvento;
    // End of variables declaration//GEN-END:variables
}
